package com.example.cameralu.testdemotbsplus0522;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cameralu.app.AppSharePreferences;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import tbsplus.tbs.tencent.com.tbsplus.TbsPlus;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;
    private EditText mEditText;


    private MyTBSWebView webView;
    private Context context;
    private StringBuilder eatThings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        context = MainActivity.this;
        mEditText = (EditText) findViewById(R.id.mEditText);
        webView = (MyTBSWebView) findViewById(R.id.webView);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        QbSdk.initX5Environment(MainActivity.this, null);
        //允许非wifi场景下下载内核,自动下载X5内核   24M
        QbSdk.setDownloadWithoutWifi(true);


    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    webView.setVisibility(View.GONE);
                    mTextMessage.setVisibility(View.VISIBLE);
                    mEditText.setVisibility(View.VISIBLE);
                    return true;
                case R.id.navigation_openurl:
                    mTextMessage.setVisibility(View.VISIBLE);
                    mEditText.setVisibility(View.VISIBLE);
                    String url = mEditText.getText().toString();
                    //这是显示网页的方向
                    TbsPlus.openUrl(MainActivity.this, url, TbsPlus.eTBSPLUS_SCREENDIR.eTBSPLUS_SCREENDIR_SENSOR);

                    return true;
                case R.id.navigation_notifications:
                    webViewSetting();
                    return true;
            }
            return false;
        }
    };

    private void webViewSetting() {
        mTextMessage.setVisibility(View.GONE);
        mEditText.setVisibility(View.GONE);
        webView.setVisibility(View.VISIBLE);
//        webView.loadUrl("http://www.baidu.com");

        webView.addJavascriptInterface(new JSBridge(this), "hello");//hello对象
        webView.loadURL("");
        String s1 = AppSharePreferences.getEatThings(context);
        webView.showInfoFromJava(s1);

    }

    private class JSBridge {
        private Context mContext;

        public JSBridge(Context context) {
            this.mContext = context;
        }


        @JavascriptInterface
        public void showKeyboard() {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }

        //在js中调用window.hello.sendAddData(name)，便会触发此方法。
        @JavascriptInterface
        public void sendAddData(String thing) {
            Toast.makeText(mContext,"添加了   "+ thing, Toast.LENGTH_SHORT).show();
            addEatThing(thing);
        }

        //在js中调用window.hello.sendDeleData(name)，便会触发此方法。
        @JavascriptInterface
        public void sendDeleData(String thing) {
            Toast.makeText(mContext, "删除了   " + thing, Toast.LENGTH_SHORT).show();
            cancelEatThing(thing);
        }

    }

    private void addEatThing(String s) {

        eatThings = new StringBuilder(AppSharePreferences.getEatThings(context));
        if (TextUtils.isEmpty(eatThings)) {
            eatThings.append(s);
        } else {
            eatThings.append(",");
            eatThings.append(s);
        }
        AppSharePreferences.setEatThings(context, eatThings.toString());

    }

    private String cancelEatThing(String s) {
        String allString = AppSharePreferences.getEatThings(context);
        int position = allString.indexOf(s);
        int length = s.length();
        int Length = allString.length();
        String newString;
        switch (position) {
            case -1:
                AppSharePreferences.setEatThings(context, allString);
                return allString;
            case 0:
                newString = allString.substring(0, position) + allString.substring(position + length, Length);
                AppSharePreferences.setEatThings(context, newString);
                return newString;
            default:
                newString = allString.substring(0, position - 1) + allString.substring(position + length, Length);
                AppSharePreferences.setEatThings(context, newString);
                return newString;

        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        //激活WebView为活跃状态，能正常执行网页的响应
        webView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        //当页面被失去焦点被切换到后台不可见状态，需要执行onPause
        //通过onPause动作通知内核暂停所有的动作，比如DOM的解析、plugin的执行、JavaScript执行。
        webView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            //先让webview加载null内容
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            //父布局移除webview
            ((ViewGroup) webView.getParent()).removeView(webView);
            //最后webview在销毁
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
}
